package study.itheima.stusys;

import study.itheima.bean.Stu;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/ListStu")
public class ListStu extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = new BufferedReader(new FileReader("e:\\stu.txt"));
        ArrayList<Stu> list = new ArrayList<>();

        //3.循环读取文件中的数据，将数据封装到Student对象中。再把多个学生对象添加到集合中
        String line;
        while((line = br.readLine()) != null) {
            Stu stu = new Stu();
            String[] arr = line.split(",");
            stu.setStuname(arr[0]);
            stu.setStuage(Integer.parseInt(arr[1]));
            stu.setStuscore(Integer.parseInt(arr[2]));
            list.add(stu);
        }
        req.getSession().setAttribute("stu",list);
        String contextPath = req.getContextPath();
        resp.sendRedirect(contextPath+"/webstu/listStu.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
